package com.app.brilliant.sms;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.app.brilliant.common.exception.BusinessException;
import com.app.brilliant.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 阿里云短信服务
 */
@Service
public class AliyunSmsService {

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.signName}")
    private String signName;

    @Value("${aliyun.sms.templateCode}")
    private String templateCode;

    @Autowired
    private SmsVerificationCacheService cacheService;

    /**
     * 发送短信验证码
     * @param phone 手机号
     * @param code 验证码
     * @param bizType 业务类型
     * @return 是否发送成功
     */
    public boolean sendSms(String phone, String code, String bizType) {
        // 1. 检查发送频率限制（60秒内只能发送一次）
        cacheService.checkSendFrequency(phone, bizType, 60);

        // 2. 检查每日发送上限（每天最多10条）
        cacheService.checkDailyLimit(phone, bizType, 10);

        // 3. 检查IP请求频率
        String ip = IpUtil.getRequestIp();
        cacheService.checkIpFrequency(ip, 60);

        // 4. 保存验证码（有效期5分钟）
        cacheService.saveCode(phone, code, bizType, 5);
        try {
            // 初始化acsClient
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
            IAcsClient acsClient = new DefaultAcsClient(profile);

            // 组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(phone);
            request.setSignName(signName);
            request.setTemplateCode(templateCode);
            request.setTemplateParam("{'code':'".concat(code).concat("'}"));

            // 发送短信
            SendSmsResponse response = acsClient.getAcsResponse(request);
            return "OK".equals(response.getCode());
        } catch (ClientException e) {
            throw new BusinessException("短信发送失败：" + e.getMessage());
        }
    }

    /**
     * 验证短信验证码
     * @param phone 手机号
     * @param code 验证码
     * @param bizType 业务类型
     * @return 是否验证成功
     */
    public boolean verifyCode(String phone, String code, String bizType) {
        return cacheService.verifyCode(phone, code, bizType);
    }
}